var sendType;
var urlstatus;
$(function(){
	  $.getJSON("/zhgl-jzstyxx-manage/serviceAccess/selectBysendType", function (data) {
	    sendType=data;
	 });
})
function sendUrl(){
	var url=$("#sendChannel").val();
	if(url==null||url==""){
		window.wxc.xcConfirm("发送通道为空！", window.wxc.xcConfirm.typeEnum.confirm,{
			title: "提示"
		});
	}else{
		var data={
				postUrl:url,
		};
		$.ajax({
			url:"/zhgl-jzstyxx-manage/serviceAccess/setUrl",
			data:data,
		    type: 'post',
		    success:function(result){
		    	if(result.state==200){
		    		urlstatus=1;
		    		window.wxc.xcConfirm("发送通道正常！", window.wxc.xcConfirm.typeEnum.confirm,{
		    			title: "提示",
		    			btn: parseInt("0001",2), //确定按钮
		    		});
		    	}else{
		    		urlstatus=0;
		    		window.wxc.xcConfirm("发送通道异常！", window.wxc.xcConfirm.typeEnum.confirm,{
		    			title: "提示",
		    			btn: parseInt("0001",2), //确定按钮
		    		});
		    	}
		    }
		})
	}
}
var url
function clicks(e){
	urlstatus=0;
	if($("#sendChannel").val()!=sendHost){
	    url=$("#sendChannel").val();
	}
	var content = '{"host":"smtp.qq.com","port":"25","username":"632211122@qq.com","password":"123456","auth":"true","startttlsEnable":"true","startttlsRequired":"true"}';
	if(e.split(",")[0]=="1501"){
		$("#sendURL").show();// 通道测试
		$("#mail").hide();
		
		$("#channel").show();
		$("#sendChannel").val(url);
		$("#sendChannel").attr("readonly",false);
	}else if(e.split(",")[0]=="1502"){
		$("#sendURL").hide();
		$("#mail").hide();
		
		$("#channel").show();
		$("#sendChannel").val(sendHost);
		$("#sendChannel").attr("readonly","readonly");
		urlstatus=1;
	}else if(e.split(",")[0]=="1503"){
		$("#sendURL").hide();
		$("#channel").hide();	// 隐藏通道方式
		
		$("#mail").show();
		$("#sendConfig").val(content);
		urlstatus=1;
	}
}
// 新增目标应用
function addTargetApp() {
	if(targetNum==0){
		targetNum=1;
	}
	targetNum=parseFloat(targetNum)+1;
	var datas={
			"index":targetNum,
			"key":key
	}
/*	 $.ajax({
	       url:"/zhgl-jzstyxx-manage/serviceAccess/selectByList",
	       type: 'post',
	       data:datas,
	       dataType:"json",
	       success: function (data) {
	    		 if(data==true){*/
	    				// 添加虚线组合
	    				$("#dasheds").append(
	    			    	'<div class="hrsVerDiv"id="hrs'+datas.index+'">' +
	    			    		'<hr class="hrsVertical"></hr>' +
	    			    	'</div>' +
	    			    	'<hr class="shortHrs" id="hrss'+datas.index+'"></hr>'
	    				);
	    			// 添加应用
	    				$("#targetAppList").append(
	    					'<div id="sends'+datas.index+'"style="min-height:226px;">'+
	    			    		'<div class="appConf"style="width:35%;float:left;">' +
	    			    			'<div>'+
		    							'<img id="img'+datas.index+'"src="/zhgl-jzstyxx-manage/images/queueIcon/send_gray.png" class="icon" aria-hidden="true"><br>' +	
		    			    		'</div>' +
	    							'<button type="button" id="send'+datas.index+'"class="btn iconBtn" onclick="send('+datas.index+","+1+')">' +
	    			                	'配置发送方式' +
	    			                '</button>' +
	    			            '</div>'+
	    					'<div style="width:20%;float:left;">'+
	    						'<hr class="hrs" style="margin-top: 32px;"></hr>'+
	    					'</div>'+
	    					'<div class="appConf"style="width:35%;float:left;">'+
	    						'<div class="appConf"style="width:85%;float:left;">'+
	    								'<div style="width: 100%;">'+
	    									'<img id="tApp" src="/zhgl-jzstyxx-manage/images/queueIcon/selectSystem_gray.png" class="icon" aria-hidden="true">'+						

				
	    								'</div>'+
	    								'<button id="tBtn" type="button" class="btn iconBtn" onclick="checkTargetApp('+datas.index+","+1+')">'+
	    									'选择应用系统'+
	    								'</button>'+
	    						'</div>'+
	    						'<div class="delTar"style="width:15%;float:right;">'+
        							'<img height="20px;" width="20px;" src="/zhgl-jzstyxx-manage/images/red-del.png" alt="删除"onclick="delTarApp('+datas.index+')"/>'+
        						'</div>'+
        					'</div>'+
	    				'</div>'
	    				);  
/*	    		 }else{
	    			 targetNum=targetNum-1;
	    			 window.wxc.xcConfirm("请完善目标集数据后再添加！", window.wxc.xcConfirm.typeEnum.confirm,{
	    					title: "提示"
	    				});
	    		 }*/
	       }
/*	 })
}*/
//选择源应用
function checkOriginApp() {
	if(id==""||status=="1301"){
		window.location = "/zhgl-jzstyxx-manage/app/toseeByService?param=unprocessedApp&key=" + key;
	}else{
		window.wxc.xcConfirm("该主题队列已发布，源应用无法修改！", window.wxc.xcConfirm.typeEnum.confirm,{
			title: "提示",
			btn: parseInt("0001",2), //确定按钮
		});
	}
}

//选择模板
function checktemple() {
	if(id==""||status=="1301"){
		window.location = "/zhgl-jzstyxx-manage/template/toByService?param=unprocessedApp&key=" + key;
	}else{
		window.wxc.xcConfirm("该主题队列已发布，模板无法修改！", window.wxc.xcConfirm.typeEnum.confirm,{
			title: "提示",
			btn: parseInt("0001",2), //确定按钮
		});
  }
}
//移除消息模板
function removeTemplate(){
	if(id==""||status=="1301"){
		$.ajax({
			url:"/zhgl-jzstyxx-manage/serviceAccess/removeTemplate",
			data:{"key":key},
			type:"post",
			success:function(){
				window.location = "/zhgl-jzstyxx-manage/serviceAccess/page?key=" + key;
			}
		})	
	}else{
		window.wxc.xcConfirm("该主题队列已发布，模板无法修改！", window.wxc.xcConfirm.typeEnum.confirm,{
			title: "提示",
			btn: parseInt("0001",2), //确定按钮
		});
	}
}
//选择目标应用
function checkTargetApp(e,w){
	var num=e;
	var index=w;
	if(id==""||status=="1301"||w==1){
		window.location = "/zhgl-jzstyxx-manage/app/toByTargetApp?param=TargetApp&num="+num+"&key=" + key;
	}else{
		window.wxc.xcConfirm("该主题队列已发布，目标应用无法修改！", window.wxc.xcConfirm.typeEnum.confirm,{
			title: "提示",
			btn: parseInt("0001",2), //确定按钮
		});
	}
}

//选择发送方式
function send(e,w) {
	urlstatus=0;
	var num=e;
	var index=w;
	var datas={
			"key":key,
			"index":num
	}
	if(id==""||status=="1301"||w==1){
		$.ajax({
			url:"/zhgl-jzstyxx-manage/serviceAccess/selectBysend",
			type: 'post',
			data:datas,
			success: function (data) {
	          if (data!= ""&&data!=null) {
	        	  	urlstatus=0;
	        		var tpl = document.getElementById('sendTemplate').innerHTML;
	        		var html = template(tpl, {send:data});
	        		$("#myform").html(html);
	        		if(data.sendType=="1502"){
	        			urlstatus=1
	        			$("#sendChannel").attr("readonly","readonly");
	        		}
	        		$("#num").val(num);
	        		$("#sendChannel").val(data.sendChannel);
	        		$("send")
	        		var tpl2 = document.getElementById('sendTypeTemplate').innerHTML;
	        		var html2 = template(tpl2, {send:sendType,list:data});
	        		$("select[name='sendType']").html(html2);
	              	$('#myModal').modal({backdrop: 'static', keyboard: false});
		      		$(".modal-backdrop.fade.in").hide();//隐藏遮罩  
	            }else {
	            	var tpl = document.getElementById('sendTemplate').innerHTML;
	            	var html = template(tpl, {});
	            	$("#myform").html(html);
	            	$("#num").val(num);
	            	var tpl2 = document.getElementById('sendTypeTemplate').innerHTML;
	            	var html2 = template(tpl2, {send:sendType,list:""});
	            	$("select[name='sendType']").html(html2);
	              	$('#myModal').modal({backdrop: 'static', keyboard: false});
		      		$(".modal-backdrop.fade.in").hide();//隐藏遮罩  
	            }
	         }
	     });
	}else{
		window.wxc.xcConfirm("该主题队列已发布，发送方式无法修改！", window.wxc.xcConfirm.typeEnum.confirm,{
			title: "提示",
			btn: parseInt("0001",2), //确定按钮
		});
	}
}
//保存发送方式
function saveSend(){
 if (validform().form()) {
	var formData = $('#myform').serializeJSON();
//	console.log("formData",formData);
	var send=formData.sendType.split(",");
	var config = formData.sendConfig;
	console.log("JSON配置信息",JSON.stringify(config));
	  var data={
		  index:formData.num,
		  sendType:send[0],
		  sendName:send[1],
		  sendChannel:formData.sendChannel,
		  sendConfig: config,
		  key:key
		  }
	  console.log("data",data);
//	  if(urlstatus==1){
		      var option = {
						title: "提示",
						btn: parseInt("0011",2),
						onOk: function(){
							var url = "/zhgl-jzstyxx-manage/serviceAccess/saveSend";
							var datapost = data
							$.post(url, datapost, function(map) {
								if(data.index==1){
									$("#sendx").html(data.sendName);
									$("#sendx").attr("class","send btn iconBtn");
									$("#imgx").attr("src","/zhgl-jzstyxx-manage/images/queueIcon/send_blue.png");
									$('#myModal').modal('hide');
								}
									$("#send"+data.index).html(data.sendName);
									$("#send"+data.index).attr("class","send btn iconBtn");
									$("#img"+data.index).attr("src","/zhgl-jzstyxx-manage/images/queueIcon/send_blue.png");
									$('#myModal').modal('hide');
							});
						}
					}
			window.wxc.xcConfirm("是否保存？", "custom", option);
	  
//	  }else{
//		  window.wxc.xcConfirm("请测试通道是否正常后再保存", window.wxc.xcConfirm.typeEnum.confirm,{
//				title: "提示",
//				btn: parseInt("0001",2), //确定按钮
//			});
//	  }
	
 }
}
// 返回主题队列管理页面
function backQueue() {
/*	var option = {
		title: "提示",
		btn: parseInt("0011",2),
		onOk:function(){
			window.location = "/zhgl-jzstyxx-manage/topicQueue/page";
		}
	}
	window.wxc.xcConfirm("是否返回主题队列管理页面？", "custom", option);*/
	var option = {
			title: "提示",
			btn: parseInt("0011",2),
			onOk: function(){
				var url = "/zhgl-jzstyxx-manage/serviceAccess/deleteSession";
				var datapost = {
					"key" : key,
				}
				$.post(url, datapost, function() {
							window.location = "/zhgl-jzstyxx-manage/topicQueue/page";
					})
				}
			}
		window.wxc.xcConfirm("是否返回主题队列管理页面？", "custom", option);
 }

//保存按钮
function save() {
if (valid().form()) {
	var topicQueueName = $("#topicServiceName").val();
	var datapost = {
			"key" : key,
			"topicQueueName":topicQueueName
		}
	console.log("datapost保存", datapost);
	$.ajax({
		url:"/zhgl-jzstyxx-manage/serviceAccess/inspect",
		data:datapost,
		dataType:"json",
		type:"post",
		success:function(data){
			if(data==0){
				if(id!=null&&id!=""){
					var option = {
							title: "提示",
							btn: parseInt("0011",2),
							onOk: function(){
								var url = "/zhgl-jzstyxx-manage/serviceAccess/updateServiceAccess";
								$.post(url, datapost, function(data) {
  									if(data.state==200){
										$.ajax({
											url:"/zhgl-jzstyxx-manage/serviceAccess/deleteSession",
											data:{"key":key},
											success: function () {
													window.location = "/zhgl-jzstyxx-manage/topicQueue/page";
											}
										});
									}else{
										window.wxc.xcConfirm("数据修改异常", window.wxc.xcConfirm.typeEnum.confirm,{
														title: "提示",
														btn: parseInt("0001",2), //确定按钮
													});
									}
								});
								
							}
						}
						window.wxc.xcConfirm("是否修改此此主题队列？", "custom", option);
				}else{
				 var option = {
						title: "提示",
						btn: parseInt("0011",2),
						onOk: function(){
							var url = "/zhgl-jzstyxx-manage/serviceAccess/saveServiceAccess";
							$.post(url, datapost, function(data) {
								if(data.state==200){
									$.ajax({
										url:"/zhgl-jzstyxx-manage/serviceAccess/deleteSession",
										data:{"key":key},
										success: function () {
												window.location = "/zhgl-jzstyxx-manage/topicQueue/page";
										}
									});
								}else{
									window.wxc.xcConfirm("数据修改异常", window.wxc.xcConfirm.typeEnum.confirm,{
										title: "提示",
										btn: parseInt("0001",2), //确定按钮
									});
								}
							});
							
						}
					}
					window.wxc.xcConfirm("是否保存此主题队列？", "custom", option);
					}
			}else{
   			 if(data==1){
   				window.wxc.xcConfirm("请完成全部填写后再保存！", window.wxc.xcConfirm.typeEnum.confirm,{
					title: "提示",
					btn: parseInt("0001",2), //确定按钮
				});
   			 }else if(data==2){
   				window.wxc.xcConfirm("请完善主题名称再保存！", window.wxc.xcConfirm.typeEnum.confirm,{
					title: "提示",
					btn: parseInt("0001",2), //确定按钮
				});
   			 }else if(data==3){
   				window.wxc.xcConfirm("请完善源应用再保存！", window.wxc.xcConfirm.typeEnum.confirm,{
					title: "提示",
					btn: parseInt("0001",2), //确定按钮
				});
   			 }else if(data==5){
   				window.wxc.xcConfirm("请完善目标应用再保存！", window.wxc.xcConfirm.typeEnum.confirm,{
					title: "提示",
					btn: parseInt("0001",2), //确定按钮
				});
   			 }else if(data==6){
    				window.wxc.xcConfirm("请完善目标应用再保存！", window.wxc.xcConfirm.typeEnum.confirm,{
    					title: "提示",
    					btn: parseInt("0001",2), //确定按钮
    				});
       			 }
			}
		}
	})
}else{
	window.wxc.xcConfirm("请完善主题名称再保存！", window.wxc.xcConfirm.typeEnum.confirm,{
		title: "提示",
		btn: parseInt("0001",2), //确定按钮
	});
}
}
//保存主题队列名称
function saveServiceName(){
		var name=$("#topicServiceName").val();
		if(name!=null&&name!=""){
			var data={
					key:key,
					ServiceName:name
				}
			$.post("/zhgl-jzstyxx-manage/serviceAccess/saveName",data);
		}
}
//删除
function delTarApp(e){
	var index=e;
	var data={
			key:key,
			index:index
	}
	if(index==1){
		$.ajax({
			url:"/zhgl-jzstyxx-manage/serviceAccess/removeTargetApp",
			data:data,
			success:function(data){
				if(targetNum>1){
					targetNum=targetNum-1
					window.location = "/zhgl-jzstyxx-manage/serviceAccess/page?key=" + key;
				}else{
					window.location = "/zhgl-jzstyxx-manage/serviceAccess/page?key=" + key;
				}
			}
		})
	}else{
		var div=$("#sends"+index);
		var div2=$("#hrs"+index);
		var hr=$("#hrss"+index);
		$.ajax({
			url:"/zhgl-jzstyxx-manage/serviceAccess/removeTargetApp",
			data:data,
			success:function(){
				/*div.remove();
				div2.remove();
				hr.remove();*/
				targetNum=targetNum-1
				window.location = "/zhgl-jzstyxx-manage/serviceAccess/page?key=" + key;
			}
		})
	}
}
function validform() {
    return $("#myform").validate({
        rules: {
        	sendType:{
                required:true,
        	},
        	sendChannel: {
                required: true,
                isUrl:true,
            },
            sendConfig: {
                required: true,
                isjson:true,
            }
        },
		     messages: {
		    	 sendType:{
		             required:"发送方式不能为空",
		        },
		        sendChannel: {
		             required: "发送通道不能为空",
		             isUrl:jQuery.validator.addMethod("isUrl", function(value, element) {
		            	 	var mobile = /[a-zA-z0-9.]+[:^\s]*/;
		            	 	return this.optional(element) || (mobile.test(value));
		             		}, "请正确填写url")
		        },
		        sendConfig: {
		             required: "邮箱配置不能为空",
		             isjson:jQuery.validator.addMethod("isjson", function(value, element) {
		            	 var all = /^[0-9]+$/;
		            	 try {
		            		 if(value.trim()!='') {
			            		 if(all.test(value.trim())) {
			            			 return false;
			            		 }
			            		 var obj=JSON.parse(value.trim());
		            		 }
		            		 return true;
		            	 }catch(e) {	// 不是json会报异常
		            		 return false;
		            	 }
		             }, '数据格式不对，请参考{"host":"smtp.qq.com","port":"25"}此JSON格式！')
		        }
		 },
    })
}
//校验输入框
function valid() {
	
    return $("#serviceAccess").validate({
		rules: {
			topicServiceName: {
                required:true,
                maxlength:32,
                remote:{
            	    url:"/zhgl-jzstyxx-manage/serviceAccess/checkName",
              	    type:"post",
                    dataType:"json",
                    async:false,
                    cache:false,
                    data:{
                    	name:function(){
                 		  var name=$("#topicServiceName").val();
                		    return name;
                	 	   },
                	 	   id:function(){
                      		  var ids=id;
                      		  return ids;
                  	 	   },
                 	},
        		       dataFilter:function(data){
        				  return data;
        		       }
                },
                stringCheck:true,
			},
			
		},
    	messages: {
    		//对应name
    		topicServiceName: {
	             required:"主题队列名称不能为空",
	             maxlength:"最多输入32位",
	             remote:"主题名重复",
	             stringCheck:jQuery.validator.addMethod("stringCheck", function(value, element) {
	            	 var all= /^[a-zA-Z0-9\u4e00-\u9fa5]+$/;
	                 return this.optional(element) || all.test(value);       
	             }, "不能有特殊字符")
    		},
    		
    		
    	}
	});
}